const allServices = require('../../controller/mysql')

const cart = {
    cartList: (req, res) => {
        console.log(req.user, 1111);
        const sql = `SELECT s.*, c.shop_count FROM shoplist s
        JOIN (
          SELECT shop_id, shop_count
          FROM cart
          WHERE user_id = ?
        ) as c ON s.shop_id = c.shop_id`;
        const userId = req.user.user_id;
        allServices.query(sql, [userId])
            .then((result) => {
                res.send({
                    code: 200,
                    msg: '请求成功',
                    res: result
                });
            })
            .catch((error) => console.log(error));
    },
    countChange: (req, res) => {
        const shopCount = req.body.value;
        const shopId = req.body.name;
        const userId = req.user.user_id;
        if (!shopCount || !shopId || !userId) {
            return res.status(400).send({
                code: 400,
                msg: '缺少必要的参数'
            });
        } else {
            const sql = `UPDATE cart SET shop_count = ? WHERE shop_id = ? AND user_id = ?`;
            allServices.query(sql, [shopCount, shopId, userId])
                .then(() => {
                    res.send({
                        code: 200,
                        msg: 'success'
                    });
                })
                .catch((error) => {
                    res.status(500).send({
                        code: 500,
                        msg: '服务端错误'
                    })
                });
        }
    },
    addCart: async (req, res) => {
        const userId = req.user.user_id;
        const shopId = req.body.shop_id;
        const shopCount = req.body.shop_count;

        if (!userId || !shopId || !shopCount) {
            return res.status(400).send({
                code: 400,
                msg: '缺少必要的参数'
            });
        }

        try {
            const result = await checkCart(userId, shopId);
            if (result.length) {
                res.send({
                    code: 200,
                    msg: '该商品已添加过购物车'
                });
            } else {
                const result2 = await insertCart(userId, shopId, shopCount);
                if (result2.affectedRows) {
                    res.send({
                        code: 200,
                        msg: '成功添加购物车'
                    });
                }
            }
        } catch (error) {
            console.log(error);
            res.status(500).send({
                code: 500,
                msg: '服务器错误'
            });
        }
    },
    deleteCart: async (req, res) => {
        const userId = req.user.user_id;
        const shopId = req?.body?.shop_id;
        if (!userId || !shopId) {
            return res.status(400).send({
                code: 400,
                msg: '参数错误',
            });
        }

        try {
            await deleteCartItem(userId, shopId);
            res.send({
                code: 200,
                msg: 'success',
            });
        } catch (error) {
            res.status(500).send({
                code: 500,
                msg: '删除购物车信息失败，请稍后再试',
                detail: error.message,
            });
        }
    }
}

// 检查是否已经加入购物车
function checkCart(userId, shopId) {
    const sql = `SELECT * FROM cart WHERE user_id = ? AND shop_id = ?`;
    return allServices.query(sql, [userId, shopId]);
}
// 加入购物车
function insertCart(userId, shopId, shopCount) {
    const sql = `INSERT INTO cart (user_id, shop_id, shop_count) VALUES (?, ?, ?)`;
    return allServices.query(sql, [userId, shopId, shopCount]);
}
// 删除购物车
async function deleteCartItem(userId, shopId) {
    const sql = 'DELETE FROM cart WHERE user_id = ? AND shop_id = ?';
    const result = await allServices.query(sql, [userId, shopId]);
    if (!result.affectedRows) {
        throw new Error('删除失败');
    }
}

module.exports = cart